package com.gitee.xhs.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author BigHead
 * @date 2022/6/29 16:20
 * @description FileUtil
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    private static final String METADATA_NAME = "_metadata";

    public static void createDir(String createDirPath) {
        File dir = new File(createDirPath);
        if (!dir.exists()) {
            logger.info("文件夹创建[" + dir.getName() + "] =>" + dir.mkdirs());
        }
    }

    public static Map<String, String> listHasStateFilePath(String baseFilePath) {
        Map<String, String> pathMap = new HashMap<>();
        File baseDir = new File(baseFilePath);
        if (baseDir.isDirectory()) {
            // 循环任务名称
            for (File jobIdDir : Objects.requireNonNull(baseDir.listFiles())) {
                if (jobIdDir.isDirectory()) {
                    // 查找 _metadata
                    String checkpointPath = getMetadataPathName(jobIdDir);
                    if (null != checkpointPath) {
                        pathMap.put(jobIdDir.getName(), checkpointPath);
                    }
                }
            }
        }
        return pathMap;
    }

    private static String getMetadataPathName(File readySearchDir) {
        for (File tempDir : Objects.requireNonNull(readySearchDir.listFiles())) {
            if (tempDir.isDirectory()) {
                return getMetadataPathName(tempDir);
            } else {
                if (checkMetadataDir(tempDir)) {
                    return readySearchDir.getAbsolutePath();
                }
            }
        }
        return null;
    }

    private static Boolean checkMetadataDir(File readyCheckMetadataFile) {
        return readyCheckMetadataFile.getName().equals(METADATA_NAME);
    }

}
